app.controller('knowledgeManagerCtrl', ["$rootScope", "$scope", "i18nService", "$state", "$timeout", "$interval", "SweetAlert", "$modal", "FileUploader", "i18nService", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_user_data", "api_solution", "api_bpm_domain", function($rootScope, $scope, i18nService, $state, $timeout, $interval, SweetAlert, $modal, FileUploader, i18nService, uiGridConstants, uiGridGroupingConstants, Restangular, api_user_data, api_solution, api_bpm_domain) {
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    var loginUser = $rootScope.user;
    // console.log(' loginUser='+JSON.stringify( loginUser));
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';
    i18nService.setCurrentLang($scope.lang);
    //for test
    // loginUser = {
    //   id:2,
    //   name:'李进'
    // };
    //console.log(loginUser);

    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = false;
    $scope.gridOptions.enableGridMenu = false;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = false;
    $scope.gridOptions.fastWatch = true;
    // $scope.gridOptions.useExternalFiltering=true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = false;

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };

    $scope.transferTime = function(time) {
        return moment(time).format('YYYY-MM-DD');
        // // console.log(' time='+JSON.stringify( time));
        // function checkTime(i){
        //   if(i<10) return "0"+1;
        //   return i;
        // }
    }
    $scope.detailSolution = function(id) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/detailknowledge.html',
            controller: function($scope, $modalInstance, APIService, uploader, tree_data, currentUser) {
                var typeName;

                $scope.uploader = uploader;
                var loadData = function() {

                    $scope.visions = [];
                    $scope.solutionDowpath = APIService.getSolutionDowpath().getRequestedUrl();
                    APIService.findSolutionById(id).then(function(response) {
                        var datas = response.data;
                        $scope.entity = {};
                        $scope.visions = datas;
                        // console.log('datas='+JSON.stringify( datas));
                        var data = {};
                        for (var i = 0; i < datas.length - 1; i++) {
                            if (id == datas[i].id) {
                                data = datas[i];
                            }
                        }
                        var range = {};
                        for (var index = 0; index < datas.length; index++) {
                            // console.log($scope.ranges[index].id +"=="+ data.solutionRange);
                            if ($scope.ranges[index].id == data.solutionRange) {
                                range = $scope.ranges[index];
                            }
                        }
                        $scope.entity = {
                            "id": data.id,
                            "title": data.title,
                            "keys": data.keywords,
                            "typeId": data.typeId,
                            "range": range,
                            "number": data.solutionNumber,
                            "content": data.content,
                            "createrUserId": data.createrUserId,
                            "createrUserName": data.createrUserName,
                            "createTime": data.createTime,
                            "status": data.status,
                            "hits": data.hits,
                            "relateId": data.relateId,
                            "vision": data.vision,
                            "fileContent": data.fileContent,
                            // "filePic":$scope.filePic,
                            "typeName": data.typename,
                            "fileName": data.fileName,
                            "remark": data.remark,
                            "reject": data.reject
                        };
                        // APIService.getSolutionType(data.typeId).then(function(responseData){
                        //        var dd=responseData.data;
                        setInterval(function() {
                            if ($scope.entity.content == "") {
                                $scope.entity.content = data.content
                                $scope.$apply()
                            }
                        }, 1000);


                        // console.log(' $scope.entity='+JSON.stringify( $scope.entity));
                        $scope.nowEntity = data;
                        $scope.couldReview = true;
                        $scope.showOutTime = true;

                        if ($scope.nowEntity.status != 1) { //状态只有是 待审核状态 才能进行审核
                            $scope.couldReview = false;
                        }
                        if ($scope.nowEntity.status == 2) { //表示状态为已通过&&outtime
                            $scope.showOutTime = false;
                        }
                        // console.log(' $scope.entity='+JSON.stringify( $scope.entity));
                    });
                    // });
                }

                loadData();

                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };
                $scope.uploader = uploader;
                // console.log('$scope.uploader='+JSON.stringify($scope.uploader));
                // Called when the editor is completely ready.
                $scope.onReady = function() {
                    // ...

                };
                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };
                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];


            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                uploader: function() {
                    return $scope.uploader;
                },

                tree_data: function() {

                    return angular.copy($scope.tree_data);
                },

                currentUser: function() {
                    return loginUser.id;
                }
            }
        });

    }


    $scope.editSolution = function(id) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/editorknowledge.html',
            controller: function($scope, $modalInstance, APIService, uploader, tree_data, currentUser) {
                var typeName;
                $scope.tree_handler = function(branch) {
                    $scope.showknowledgeType = true;
                    $scope.entity.typeName = branch.label;
                    $scope.entity.typeId = branch.id;
                    // console.log(branch);
                };

                $scope.data = tree_data;
                $scope.showknowledgeType = false;

                $scope.chooseknowledge = function() {
                    $scope.showknowledgeType = !$scope.showknowledgeType;
                }
                $scope.close = function() {
                    $scope.showknowledgeType = false;
                };

                $scope.uploader = uploader;
                var loadData = function() {
                    $scope.entity = {};
                    $scope.visions = [];
                    $scope.solutionDowpath = APIService.getSolutionDowpath().getRequestedUrl();
                    APIService.findSolutionById(id).then(function(response) {
                        var datas = response.data;
                        // console.log('datas='+JSON.stringify(datas));
                        $scope.visions = datas;
                        // console.log(' datas='+JSON.stringify( datas));
                        var data = {};
                        for (var i = 0; i < datas.length - 1; i++) {
                            if (id == datas[i].id) {
                                data = datas[i];
                            }
                        }
                        var range = {};
                        for (var index = 0; index < datas.length; index++) {
                            // console.log($scope.ranges[index].id +"=="+ data.solutionRange);
                            if ($scope.ranges[index].id == data.solutionRange) {
                                range = $scope.ranges[index];
                            }
                        }
                        $scope.entity = {
                            "id": data.id,
                            "title": data.title,
                            "keys": data.keywords,
                            "typeId": data.typeId,
                            "range": range,
                            "number": data.solutionNumber,
                            "content": data.content,
                            "createrUserId": data.createrUserId,
                            "createrUserName": data.createrUserName,
                            "renewUserName": data.renewUserName,
                            "approveUserName": data.approveUserName,
                            "createTime": moment(data.createTime).format('YYYY-MM-DD HH:mm:ss'),
                            "renewTime": moment(data.renewTime).format('YYYY-MM-DD HH:mm:ss'),
                            "updateTime": moment(data.updateTime).format('YYYY-MM-DD HH:mm:ss'),
                            "approveTime": moment(data.approveTime).format('YYYY-MM-DD HH:mm:ss'),
                            "status": data.status,
                            "hits": data.hits,
                            "relateId": data.relateId,
                            "vision": data.vision,
                            "vision2": "V" + data.vision,
                            "fileContent": data.fileContent,
                            // "filePic":$scope.filePic,
                            "typeName": data.typename,
                            "fileName": data.fileName,
                            "remark": data.remark
                        };
                        // APIService.getSolutionType(data.typeId).then(function(responseData){
                        //        var dd=responseData.data;


                        setInterval(function() {
                            if ($scope.entity.content == "") {
                                $scope.entity.content = data.content
                                $scope.$apply()
                            }
                        }, 1000);
                        $scope.nowEntity = data;
                        $scope.couldReview = true;
                        $scope.showOutTime = true;

                        if ($scope.nowEntity.status != 1) { //状态只有是 待审核状态 才能进行审核
                            $scope.couldReview = false;
                        }
                        if ($scope.nowEntity.status == 2) { //表示状态为已通过&&outtime
                            $scope.showOutTime = false;
                        }
                        // console.log(' $scope.entity='+JSON.stringify( $scope.entity));
                    });
                    // });
                }

                loadData();

                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };
                $scope.uploader = uploader;
                $scope.onReady = function() {
                    // ...

                };

                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];


                $scope.ok = function() {
                    $modalInstance.close($scope.entity);
                };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };
            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                uploader: function() {
                    return $scope.uploader;
                },

                tree_data: function() {

                    return angular.copy($scope.tree_data);
                },

                currentUser: function() {
                    return loginUser.id;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            if (selectedItem) {
                if ($scope.uploader.getNotUploadedItems().length > 0) {
                    // console.log("$scope.uploader.getNotUploadedItems() ");
                    // console.log('selectedItem='+JSON.stringify(selectedItem));
                    $scope.uploader.formData = [
                        { 'id': selectedItem.id },
                        { 'title': selectedItem.title },
                        { 'createrUserId': selectedItem.createrUserId },
                        { 'content': selectedItem.content },
                        { 'hits': 0 },
                        { 'keywords': selectedItem.keys },
                        { 'solutionNumber': selectedItem.number },
                        { 'typeId': selectedItem.typeId },
                        { 'status': selectedItem.status },
                        { 'relateId': selectedItem.relateId },
                        { 'vision': selectedItem.vision },
                        { 'solutionRange': selectedItem.range.id },
                        { 'renewUserId': loginUser.id }
                    ];
                    // console.log('$scope.uploader.formData='+JSON.stringify($scope.uploader.formData));
                    $scope.uploader.onBeforeUploadItem = function(item) {
                        item.url = api_solution.update($scope.uploader.formData).getRequestedUrl();
                        item.formData = $scope.uploader.formData;
                        item.formData.push({ 'fileName': item.file.name, 'fileContent': item.file.Content });

                    };
                    $scope.uploader.onSuccessItem = function(item, response, status, headers) {
                        if (response.status == 201) {
                            //success;
                            SweetAlert.swal({
                                title: "修改成功!",
                                text: "修改知识库成功!",
                                type: "success"
                            }, function() {
                                $scope.reload();
                            });
                        } else {
                            //error
                            SweetAlert.swal({
                                title: "修改失败!",
                                text: "修改知识库失败!",
                                type: "error"
                            });
                        }
                        //console.log(response);
                    }
                    $scope.uploader.uploadAll();

                } else {
                    var data = {
                        'id': selectedItem.id,
                        'title': selectedItem.title,
                        'createrUserId': selectedItem.createrUserId,
                        'content': selectedItem.content,
                        'hits': 0,
                        'keywords': selectedItem.keys,
                        'solutionNumber': selectedItem.number,
                        'typeId': selectedItem.typeId,
                        'status': selectedItem.status,
                        'relateId': selectedItem.relateId,
                        'vision': selectedItem.vision,
                        'solutionRange': selectedItem.range.id,
                        'renewUserId': loginUser.id
                    };
                    api_solution.updateNotFile(data).then(function(response) {
                        var myData = Restangular.stripRestangular(response);
                        // console.log('myData='+JSON.stringify(myData));
                        // console.log('response.status='+JSON.stringify(response.status));

                        if (response.status == 201) {
                            //success;
                            SweetAlert.swal({
                                title: "修改成功!",
                                text: "修改知识库成功!",
                                type: "success"
                            }, function() {
                                $scope.reload();
                            });
                        } else {
                            //error
                            SweetAlert.swal({
                                title: "修改失败!",
                                text: "修改知识库失败!",
                                type: "error"
                            });
                        }
                    });
                }
            }
        });
    }

    $scope.commentSolution = function(id) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/commentknowledge.html',
            controller: function($scope, $modalInstance, APIService, uploader, currentUser, Alert, MomentFormat) {
                $scope.uploader = uploader;
                var loadData = function() {
                    $scope.visions = [];
                    $scope.entity = {};
                    $scope.solutionDowpath = APIService.getSolutionDowpath().getRequestedUrl();
                    APIService.findSolutionById(id).then(function(response) {
                        var datas = response.data;
                        console.log(datas);
                        $scope.visions = datas;
                        // console.log(datas);
                        var data = {};
                        for (var i = 0; i < datas.length - 1; i++) {
                            if (id == datas[i].id) {
                                data = datas[i];
                            }
                        }
                        console.log(data);
                        $scope.entity = {
                            "id": data.id,
                            "title": data.title,
                            "keys": data.keywords,
                            "type": data.typeId,
                            "range": data.solutionRange,
                            "number": data.solutionNumber,
                            "content": data.content,
                            "createrUserId": data.createrUserId,
                            "createrUserName": data.createrUserName,
                            "createTime": data.createTime,
                            "status": data.status,
                            "hits": data.hits,
                            "relateId": data.relateId,
                            "vision": data.vision,
                            "vision2": "V" + data.vision,
                            "fileContent": data.fileContent,
                            "replies": data.replies,
                            "scores": data.scores,
                            "hits": data.hits,
                            "fileName": data.filename,
                            "typeName": data.typename
                        };
                        $scope.file = data.fileName;
                        $scope.nowEntity = data;
                        $scope.couldReview = true;
                        $scope.showOutTime = true;

                        if ($scope.nowEntity.status != 1) { //状态只有是 待审核状态 才能进行审核
                            $scope.couldReview = false;
                        }
                        if (($scope.nowEntity.status == 2) && outtime) { //表示状态为已通过
                            $scope.showOutTime = false;
                        }

                        $scope.comments = [];
                        APIService.findSolutionReviewById(data.id).then(function(response) {
                            if (response.status != "500") {
                                var data = response.data;
                                // console.log("data="+data);
                                for (var i = 0; i < data.length; i++) {
                                    var object = {};
                                    object.id = data[i].id;
                                    object.name = data[i].name;
                                    // object.content=data[i].review;
                                    var ss = data[i].review;
                                    var s1 = "";
                                    if (ss != null) {
                                        var index = ss.indexOf("<p>");
                                        var indexs = ss.indexOf("</p>");
                                        s1 = ss.substring(index + 3, indexs);
                                    }

                                    object.content = s1;
                                    object.score = data[i].reviewScore;
                                    object.time = MomentFormat(data[i].reviewTime).format('YYYY-MM-DD ');
                                    // console.log("object="+object );

                                    $scope.comments.push(object);
                                }
                            }
                        });





                        $scope.showCommentScore = true;
                        //查询用户是否已经评过分
                        $scope.findCommentScore = function() {
                            $scope.showCommentScore = true;
                            APIService.checkCommentScoreByUserIds(currentUser, data.id).then(function(response) {
                                var data = response.data;
                                if (data.length > 0) {
                                    $scope.showCommentScore = false;
                                    //$scope.comments = data;
                                }
                            });
                        }

                        $scope.findCommentScore();
                    });
                    // });
                }

                loadData();

                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };
                $scope.uploader = uploader;


                $scope.onReady = function() {
                    // ...

                };

                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];

                // $scope.ok = function() {
                //        $modalInstance.close($scope.entity);                
                //      };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };

                $scope.saveComment = function(reviewcontent, score) {
                    $scope.entity['reviewcontent'] = reviewcontent;
                    $scope.entity['score'] = score;
                    $modalInstance.close($scope.entity);
                    // console.log(currentUser);
                    // return;
                    // var solutionId=$scope.entity.id;

                    // console.log("solutionId111="+solutionId + " reviewcontent:"+reviewcontent);
                    // var reviewContent=reviewcontent;
                    // // if(solutionId==null){
                    //   var data = {id:null,solutionId:solutionId,
                    //     userId:currentUser,review:reviewContent,reviewScore:score,reviewTime:new Date()};
                    //   APIService.addSolutionReview(data).then(function(response){
                    //       console.log('$scope.apClient=');
                    //       var status=response.status;
                    //       console.log('$scope.apClient='+JSON.stringify(status));
                    //       if(status=="201"){
                    //        var data=response.data;
                    //        //$scope.comments.push({id:data.id,solutionId:data.solutionId,
                    //        //userId:data.userId,name:loginUser.name,score:data.reviewScore,
                    //        //content:data.review,time:data.reviewTime});

                    //        $scope.reviewcontent="";
                    //        $scope.score=0;
                    //        Alert.swal({
                    //           title: "评论知识库!",
                    //           text: "评论知识库成功!",
                    //           type: "success"
                    //        }); 
                    //       }else{
                    //         Alert.swal({
                    //           title: "评论知识库!",
                    //           text: "评论知识库失败!",
                    //           type: "error"
                    //        }); 
                    //       }

                    //    });
                }


            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                uploader: function() {
                    return $scope.uploader;
                },
                currentUser: function() {
                    return loginUser.id;
                },
                Alert: function() {
                    return SweetAlert;
                },
                MomentFormat: function() {
                    return moment;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            console.log('selectedItem=' + JSON.stringify(selectedItem));
            // console.log('reviewContent='+JSON.stringify(reviewContent));
            // console.log('score='+JSON.stringify(score));

            if (selectedItem) {

                var solutionId = selectedItem.id;
                var reviewContent = selectedItem.reviewcontent;
                // if(solutionId==null){
                var data = {
                    id: null,
                    solutionId: solutionId,
                    userId: loginUser.id,
                    review: reviewContent,
                    reviewScore: selectedItem.score,
                    reviewTime: new Date()
                };
                api_solution.addSolutionReview(data).then(function(response) {
                    var status = response.status;
                    console.log(response)
                    console.log('$scope.apClient=' + JSON.stringify(status));
                    if (status == "201") {
                        // var data=response.data;
                        // $scope.reviewcontent="";
                        // $scope.score=0;
                        SweetAlert.swal({
                            title: "评论知识库!",
                            text: "评论知识库成功!",
                            type: "success"
                        }, function() {
                            $scope.reload();
                        });
                    } else {
                        SweetAlert.swal({
                            title: "评论知识库!",
                            text: "评论知识库失败!",
                            type: "error"
                        });
                    }

                });
            }
        });


    }

    $scope.approvalSolution = function(id, outTimePower) {

        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/approvalknowledge.html',
            controller: function($scope, $modalInstance, APIService, Alert, workGroups, uploader, tree_data, outTimePower) {
                $scope.wgroups = workGroups;

                $scope.type_handler = function(branch) {
                    $scope.typeIds = branch.id;
                    // console.log(branch);
                };
                $scope.type_data = tree_data;


                $scope.uploader = uploader;

                var loadData = function() {
                    $scope.visions = [];
                    APIService.findSolutionById(id).then(function(response) {
                        var datas = response.data;
                        $scope.visions = datas;
                        //console.log(datas);
                        var data = {};
                        for (var i = 0; i < datas.length - 1; i++) {
                            if (id == datas[i].id) {
                                data = datas[i];
                            }
                        }
                        $scope.entity = {
                            "id": data.id,
                            "title": data.title,
                            "keys": data.keywords,
                            "typeId": data.typeId,
                            "range": data.solutionRange,
                            "number": data.solutionNumber,
                            "content": data.content,
                            "createrUserId": data.createrUserId,
                            "createrUserName": data.createrUserName,
                            "createTime": data.createTime,
                            "status": data.status,
                            "hits": data.hits,
                            "relateId": data.relateId,
                            "vision": data.vision,
                            "outtime": outTimePower,
                            // "filePic":$scope.filePic,
                            "typeName": data.typename,
                            "fileName": data.fileName
                        };
                        // var typeName;
                        // APIService.getSolutionType(data.typeId).then(function(responseData){
                        //        var dd=responseData.data;
                        //        typeName=dd.typeName;

                        // console.log('$scope.entity_2='+JSON.stringify($scope.entity));
                        $scope.nowEntity = data;
                        $scope.couldReview = true;
                        $scope.showOutTime = true;
                        $scope.fabu = false;
                        $scope.shenhe = false;
                        $scope.fabulabel = false;
                        $scope.chexiao = false;
                        $scope.shouquan = false;
                        //$scope.shou=false;


                        if ($scope.nowEntity.status != 1) { //状态只有是 待审核状态 才能进行审核
                            $scope.couldReview = false;
                        }
                        if ($scope.nowEntity.status == 1) {
                            $scope.shenhe = true;
                            if ($scope.entity.range == 3) {
                                $scope.shouquan = true;
                                api_solution.findSolutionGroup($scope.entity.id).then(function(response) {
                                    $scope.multipleDemo = {};
                                    var data = response.data;
                                    var item = [];
                                    $scope.multipleDemo.id = $scope.entity.id;
                                    for (var i = 0; i < $scope.group.length; i++) {
                                        for (var j = 0; j < data.length; j++) {
                                            if (data[j].groupId == $scope.group[i].id) {
                                                item[item.length] = $scope.group[i];
                                                break;
                                            }
                                        }
                                    }
                                    $scope.multipleDemo.item = item;
                                    $scope.multipleDemo;
                                });
                            }
                        }
                        if ($scope.nowEntity.status == 2) {
                            $scope.fabu = true;
                            $scope.fabulabel = true;
                        }
                        if ($scope.nowEntity.status == 3) {
                            $scope.fabu = false;
                            $scope.chexiao = true;
                            $scope.showOutTime = false;
                        }
                        // if($scope.nowEntity.status==4){
                        //     $scope.fabu=true;
                        //     $scope.chexiao = true;
                        // }

                        if (($scope.nowEntity.status == 2) && outTimePower) { //表示状态为已通过
                            $scope.showOutTime = false;
                        }



                        APIService.getTree($scope.typeIds, $scope.groupIds, $scope.actionType).then(function(response) {
                            var objectR = [];
                            var objectL = [];
                            var data = response.data;
                            var map = data.map;
                            var inList = map.inList;
                            var outList = map.outList;

                            if (inList != null) {
                                for (var i = 0; i < inList.length; i++) {
                                    var object = inList[i];
                                    var entity = {
                                        "id": object[0],
                                        "name": object[1],
                                        "value": object[1]
                                    }
                                    objectR.push(entity); //已选
                                }
                            }
                            if (outList != null) {
                                for (var i = 0; i < outList.length; i++) {
                                    var object = outList[i];
                                    var entity = {
                                        "id": object[0],
                                        "name": object[1],
                                        "value": object[1]
                                    }
                                    objectL.push(entity); //未选
                                }
                            }
                            $scope.peopleR = objectR;
                            $scope.peopleL = objectL;
                        });



                    });
                    // });
                }
                $scope.closeAlert = function(index) {
                    $scope.alerts.splice(index, 1);
                };
                $scope.test = false;
                $scope.getin = false;
                $scope.verifySolutions = function(type, reason) {

                    var publishRange = angular.element("#publishRange").val();
                    if (publishRange == "") {
                        publishRange = 0;
                    }

                    var status = "";
                    var statusName = "";
                    if (type == "success") { //审核通过
                        status = 2;
                        statusName = "审核通过";
                    } else if (type == "failed") { //审核驳回
                        status = 5;
                        statusName = "审核驳回";
                    } else if (type == "reject") { //审核拒绝
                        status = 6;
                        statusName = "审核拒绝";
                    } else if (type == "outtime") { //过时
                        status = 4;
                        statusName = "取消";

                    } else if (type = "publish") { //发布
                        status = 3;
                        statusName = "发布";
                    }

                    // APIService.updateSolutionStatus({id:$scope.nowEntity.id,status:status,renewUserId:loginUser.id,publishRange:0,reject:reason}).then(function(response){ 
                    //     var status=response.status;
                    //      if(status=="200"){
                    //           Alert.swal({
                    //               title: statusName+"知识库",
                    //               text: statusName+'成功',
                    //               type: "warning"
                    //           });
                    //       }else{
                    //           Alert.swal({
                    //               title: statusName+"知识库",
                    //               text: statusName+'失败',
                    //               type: "warning"
                    //           });
                    //      }
                    //       $modalInstance.dismiss('cancel');
                    // });
                    $scope.entity.status = status;
                    $scope.entity['statusName'] = statusName;
                    $scope.entity['reason'] = reason;
                    $modalInstance.close($scope.entity);
                };

                $scope.group = [];
                api_user_data.fetchDataList('group', { 'idx': 0, 'sum': 1000 }).then(function(result) {
                    $scope.my_data = convertParentToChildList(result['list']);
                    var nata = [];
                    for (var i = 0; i < $scope.my_data.length; i++) {
                        nata.push({
                            'groupname': $scope.my_data[i].groupName,
                            'id': $scope.my_data[i].id
                        })
                        $scope.group = nata;
                    }
                })

                $scope.saveright = function(multipleDemo) {
                    console.log(multipleDemo);
                    // if(angular.isUndefined(multipleDemo)){
                    //   Alert.swal({
                    //       title: "授权知识库!",
                    //       text: "授权知识库成功!",
                    //       type: "success"
                    //     }); 
                    // }
                    $scope.entity['multipleDemo'] = multipleDemo;
                    // if(angular.isDefined(multipleDemo)){
                    //   if(multipleDemo.item!=[]){ 
                    //     var item = [];
                    //     for(var i = 0;i < multipleDemo.item.length ; i++){
                    //       item[i] = multipleDemo.item[i].id;
                    //     } 

                    // api_solution.saveSolutionGroup(multipleDemo.id,item).then(function(response){
                    // $scope.data4 = response.data;
                    // console.log(data);
                    // if(response.status == "200"){
                    //   Alert.swal({
                    //     title: "授权知识库!",
                    //     text: "授权知识库成功!",
                    //     type: "success"
                    //   }); 
                    // }else{
                    //   Alert.swal({
                    //     title: "授权知识库!",
                    //     text: "授权知识库失败!",
                    //     type: "error"
                    //   });
                    // } 
                    // });
                    // }
                    // }
                }

                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };


                $scope.onReady = function() {
                    // ...

                };
                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];


                // $scope.ok = function() {
                //   var data = {};
                //   $modalInstance.close($scope.entity);                
                // };
                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };


                loadData();
            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                Alert: function() {
                    return SweetAlert;
                },
                workGroups: function() {
                    return $scope.groups;
                },
                uploader: function() {
                    return $scope.uploader;
                },
                tree_data: function() {
                    return angular.copy($scope.tree_data);
                },
                outTimePower: function() {
                    return outTimePower;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            if (selectedItem) {
                console.log(selectedItem);
                if (selectedItem.status == 2 && selectedItem.range == 3) {
                    console.log(selectedItem.multipleDemo.item);
                    if (angular.isUndefined(selectedItem.multipleDemo.item) || selectedItem.multipleDemo.item == "") {
                        SweetAlert.swal({
                            title: "授权为空",
                            text: "请选择本知识授权组",
                            type: "error"
                        });
                    } else {
                        var item = [];
                        for (var i = 0; i < selectedItem.multipleDemo.item.length; i++) {
                            item[i] = selectedItem.multipleDemo.item[i].id;
                        }
                        api_solution.saveSolutionGroup(selectedItem.multipleDemo.id, item).then(function(response) {
                            $scope.data4 = response;
                            if ($scope.data4.status == "200") {
                                api_solution.updateSolutionStatus({ id: selectedItem.id, status: selectedItem.status, renewUserId: loginUser.id, publishRange: 0, reject: selectedItem.reason }).then(function(response) {
                                    $scope.data5 = response;
                                    console.log($scope.data4);
                                    console.log($scope.data4)
                                    if ($scope.data5.status == "200") {
                                        SweetAlert.swal({
                                            title: "审核知识库",
                                            text: '审核成功',
                                            type: "warning"
                                        }, function() {
                                            $scope.reload();
                                        });
                                    } else {
                                        SweetAlert.swal({
                                            title: "审核知识库",
                                            text: '审核失败',
                                            type: "warning"
                                        });
                                    }
                                });
                            } else {
                                SweetAlert.swal({
                                    title: "授权",
                                    text: '授权失败',
                                    type: "warning"
                                });
                            }
                        });
                    }
                } else {
                    api_solution.updateSolutionStatus({ id: selectedItem.id, status: selectedItem.status, renewUserId: loginUser.id, publishRange: 0, reject: selectedItem.reason }).then(function(response) {
                        console.log(response);
                        var status = response.status;
                        if (response.status == "200") {
                            // if(status=="200"){
                            SweetAlert.swal({
                                title: selectedItem.statusName + "知识库",
                                text: selectedItem.statusName + '成功',
                                type: "warning"
                            }, function() {
                                $scope.reload();
                            });
                        } else {
                            SweetAlert.swal({
                                title: statusName + "知识库",
                                text: statusName + '失败',
                                type: "warning"
                            });
                        }
                    });
                }
            }
        })
    }


    $scope.publishSolution = function(id, outTimePower) {

        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/publishknowledge.html',
            controller: function($scope, $modalInstance, APIService, Alert, workGroups, uploader, outTimePower) {


                // $scope.publishSolutions=function(type){
                //      console.log("type="+type);
                //      var publishRange=angular.element("#publishRange").val();
                //      var reason=$scope.reason;
                //      if(publishRange==""){
                //          publishRange=0;
                //      }

                // var status="";
                // var statusName="";
                //  if(type=="outtime"){//过时
                //     status=4;
                //     statusName="取消";

                // }else if(type="publish"){//发布
                //     status=3;
                //     statusName="发布";
                // } 

                // console.log('status='+JSON.stringify(status));
                //   APIService.updateSolutionStatus({id:$scope.nowEntity.id,status:status,renewUserId:loginUser.id,publishRange:0,reject:reason}).then(function(response){

                //         console.log('id='+JSON.stringify(id));
                //         var status=response.status;
                //          if(status=="200"){
                //               Alert.swal({
                //                   title: "发布知识库",
                //                   text:  '发布成功',
                //                   type: "warning"
                //               });



                //               $modalInstance.close('true');

                //          }
                //   });

                // };

                $scope.group = [];
                api_user_data.fetchDataList('group', { 'idx': 0, 'sum': 1000 }).then(function(result) {
                    $scope.my_data = convertParentToChildList(result['list']);
                    var nata = [];
                    for (var i = 0; i < $scope.my_data.length; i++) {
                        nata.push({
                            'groupname': $scope.my_data[i].groupName,
                            'id': $scope.my_data[i].id
                        })
                        $scope.group = nata;
                    }
                    //  findSolutionGroup/
                    // api_solution.findSolutionGroup(id).then(function(response){
                    //   var data = response.data;
                    //   console.log('data='+JSON.stringify(data));
                    // })
                    //  saveSolutionGroup/  

                })

                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };


                $scope.onReady = function() {
                    // ...

                };
                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];


                $scope.ok = function() {
                    var data = {};
                    $modalInstance.close($scope.entity);
                };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };


                loadData();
            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                Alert: function() {
                    return SweetAlert;
                },
                workGroups: function() {
                    return $scope.groups;
                },
                uploader: function() {
                    return $scope.uploader;
                },
                tree_data: function() {
                    return angular.copy($scope.tree_data);
                },
                outTimePower: function() {
                    return outTimePower;
                }
            }
        });
    }




    $scope.transferStatus = function(status) {
        var statusLabel = "不合法的状态";
        if (status == 1) {
            statusLabel = "待审核";
        } else if (status == 2) {
            statusLabel = "已批准";
        } else if (status == 3) {
            statusLabel = "已发布";
        } else if (status == 4) {
            statusLabel = "已取消";
        } else if (status == 5) {
            statusLabel = "已驳回";
        } else if (status == 6) {
            statusLabel = "已拒绝";
        }
        return statusLabel;
    }

    $scope.gridOptions.columnDefs = [
        { name: '操作', width: 140, cellTemplate: '<gridoperator item="row.entity" colobject="col">' },
        { name: 'solutionNumber', displayName: '编号', width: 100 },
        { name: 'typeName', displayName: '类别', width: 100 },
        { name: 'title', displayName: '标题', width: 100 },
        { name: 'keywords', displayName: '关键字', width: 100 },
        { name: 'status', displayName: '状态', cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.transferStatus(row.entity.status)}}</div>', width: 80 },
        { name: 'creationname', displayName: '创建人', width: 60 },
        { name: 'creationTime', cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.transferTime(row.entity.creationTime)}}</div>', displayName: '创建日期', width: 100 }
    ];
    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            var filtersData = $scope.allfilterData;
            // console.log(filtersData)
            filterData.pageIndex = newPage;
            var data = { pageIndex: newPage };
            var dataFilter = angular.extend(data, filterData);
            dataFilter.status = filtersData.status;
            // console.log(dataFilter)
            $scope.refreshListData('expand-right', dataFilter);
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
            //$scope.selected.item = data.entity;
        });
        // gridApi.core.on.filterChanged($scope, function() {
        //   var grid = this.grid;
        //   var filtersData = {
        //     "assignee":$rootScope.user.id,
        //     "candidateGroups":$rootScope.user.group[0].id,
        //     idx:0,
        //     sum:10
        //   };
        //   angular.forEach(grid.columns,function(item){
        //     if(item.enableFiltering){
        //       if(angular.isDefined(item.filters[0].term)&&item.filters[0].term!=''){
        //         // console.log('item.filters[0]='+JSON.stringify(item.filters[0]));
        //         if(angular.isUndefined(filtersData['knowledge'])){
        //           filtersData['knowledge']={};
        //         }
        //         filtersData['knowledge'][item.field]=item.filters[0].term;
        //       }                                                
        //     }
        //   });
        //   // $scope.memoryfilterData = filtersData;
        //   $scope.refreshListData('expand-right', filtersData);
        // });
    };

    this.selectRowFunction = function(data) {};

    $scope.refreshListData = function(style, filterData) {
        $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            filterData['searchType'] = $scope.searchTypes;
        }
        $scope.myData = [];
        api_solution.findSolutionByKeys(filterData).then(function(data) {
            var myData = Restangular.stripRestangular(data);
            // console.log("myData="+JSON.stringify(myData));
            $scope.gridOptions.totalItems = myData.totalNum;
            if (angular.isArray(myData.data)) {
                $scope.myData = myData.data;
            } else {
                // SweetAlert.swal({
                //     title: "数据为空",
                //     text: myData.data,
                //     type: "warning"
                // });    
            }
            $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            $scope.ldloading[style.replace('-', '_')] = false;
        });
    }


    var apple_selected, tree, treedata_avm, treedata_geography;
    //$scope.selectedTreeNode = {};
    $scope.my_tree_handler = function(branch) {
        filterData.treeIds = branch.id;
        $scope.selectedTreeNode = branch;
        $scope.refreshListData('expand-right', filterData);
    };
    $scope.my_data = [];
    $scope.tree_data = [];
    $scope.my_tree = tree = {};


    function convertListToTree(data, treeMap) {
        var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
        var root = null; //Initially set our loop to null
        var parentNode = null;
        //loop over data
        for (var i = 0; i < data.length; i++) {
            var datum = data[i];
            //each node will have children, so let's give it a "children" poperty
            datum.children = [];

            //add an entry for this node to the map so that any future children can
            //lookup the parent
            idToNodeMap[datum.id] = datum;

            //Does this node have a parent?
            if (typeof datum.parent === "undefined" || datum.parent == null) {
                //Doesn't look like it, so this node is the root of the tree
                root = datum;
                treeMap[datum.id] = root;
            } else {
                //This node has a parent, so let's look it up using the id
                parentNode = idToNodeMap[datum.parent];

                //We don't need this property, so let's delete it.
                delete datum.parent;

                //Let's add the current node as a child of the parent node.
                parentNode.children.push(datum);
            }
        }
        return root;
    }

    function convertParentToChildList(data) {
        var treeMap = {};
        var list = [];
        convertListToTree(data, treeMap);
        angular.forEach(treeMap, function(item) {
            list.push(item);
        });
        return list;
    }

    //    api_solution.addNotFile({ status:status,renewUserId:loginUser.id,publishRange:0,reject:reason}).then(function(response){
    //                   var myData = Restangular.stripRestangular(response); 
    // console.log('myData='+JSON.stringify(myData));
    // })


    var uploader = $scope.uploader = new FileUploader({
        url: api_solution.addSolution().getRequestedUrl(),
        alias: "file",
        removeAfterUpload: true,
        queueLimit: 1
    });
    // console.log('uploader='+JSON.stringify(uploader));
    //  var uploader_1 = $scope.uploader = new FileUploader({


    //     url:api_solution.addNotFile().getRequestedUrl(),
    //     alias:"file",
    //     removeAfterUpload:true,
    //     queueLimit:1
    // });
    // console.log('$scope.uploader.queue='+JSON.stringify(uploader.queue.file.name));
    $scope.removeKnowledgeType = function() {
        var b = $scope.my_tree.get_selected_branch();
        if (b != null) {
            SweetAlert.swal({
                title: "确认删除?",
                text: "删除数据后，将不能恢复该数据!",
                type: "warning",
                cancelButtonText: "取消",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认删除!"
            }, function(isConfirm) {
                if (isConfirm) {
                    api_solution.removeSolutionType(b.id).then(function(response) {
                        if (response.status == 204) {
                            $scope.try_async_load();
                            SweetAlert.swal({
                                title: "删除成功!",
                                confirmButtonColor: "#007AFF"
                            });
                        } else {
                            SweetAlert.swal({
                                title: "删除失败!",
                                text: response.data,
                                confirmButtonColor: "#007AFF"
                            });
                        }
                    });
                }
            });
        } else {
            SweetAlert.swal({
                title: "删除数据错误",
                text: "无法删除,请选中一个知识库类型！",
                type: "warning"
            });
        }

    }
    $scope.editKnowledgeType = function(flag, size) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/newknowledgetype.html',
            controller: function($scope, $modalInstance, selectNode, parentNode, isCreate, Alert) {
                $scope.editNode = {};
                if (angular.isDefined(selectNode)) {
                    $scope.editNode.id = selectNode.id;
                    $scope.editNode.typeName = selectNode.label;
                }
                // console.log('parentNode='+JSON.stringify(parentNode));
                // if(parentNode==null){
                //      alert("请选择要添加类别的父类")
                //  }
                if (angular.isDefined(parentNode) && (parentNode != null)) {
                    $scope.editNode.pid = parentNode.id;
                    $scope.parentName = parentNode.label;
                    $scope.ok = function() {
                        var data = {};
                        if (isCreate) {
                            data = {
                                flag: isCreate,
                                typeName: $scope.editNode.typeName,
                                pid: $scope.editNode.pid
                            }
                        } else {
                            data = {
                                flag: isCreate,
                                id: $scope.editNode.id,
                                typeName: $scope.editNode.typeName,
                                pid: $scope.editNode.pid
                            }
                        }
                        $modalInstance.close(data);
                    };
                } else {
                    Alert.swal({
                        title: "操作错误",
                        text: "请选择要添加类别的父类！",
                        type: "warning"
                    })
                    return undefined;
                }


                $scope.ok = function() {
                    $modalInstance.close($scope.entity);
                };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };
            },
            size: size,
            resolve: {
                selectNode: function() {
                    if (!flag) {
                        return $scope.my_tree.get_selected_branch();
                    } else {
                        return undefined;
                    }
                },
                parentNode: function() {
                    if (flag) {
                        return $scope.my_tree.get_selected_branch();
                    } else {
                        var b = $scope.my_tree.get_selected_branch();
                        if (b != null) {
                            return $scope.my_tree.get_parent_branch(b);
                        }
                        return undefined;
                    }
                },
                isCreate: function() {
                    return flag;
                },
                Alert: function() {
                    return SweetAlert;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            if (selectedItem) {
                if (selectedItem.flag) {
                    api_solution.addSolutionType({ "pid": selectedItem.pid, "typeName": selectedItem.typeName }).then(function(response) {
                        var myData = Restangular.stripRestangular(response);
                        var data = myData.data;
                        if (myData.status == 201) {
                            $scope.try_async_load();
                            SweetAlert.swal({
                                title: "操作成功",
                                text: "操作成功！",
                                type: "success"
                            });
                        }

                    })
                } else {
                    api_solution.updateSolutionType({ "id": selectedItem.id, "pid": selectedItem.pid, "typeName": selectedItem.typeName }).then(function(response) {
                        var myData = Restangular.stripRestangular(response);
                        var data = myData.data;
                        if (myData.status == 201) {
                            $scope.try_async_load();
                            SweetAlert.swal({
                                title: "操作成功",
                                text: "操作成功！",
                                type: "success"
                            });
                        }
                    })
                }
            }
        });
    }

    $scope.createKnowledge = function(size) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/newknowledge.html',
            controller: function($scope, $modalInstance, uploader, tree_data, APIService, currentUser, Alert) {
                $scope.createSolution = {};
                $scope.createSolution.createrUserId = currentUser;
                $scope.tree_handler = function(branch) {
                    $scope.showknowledgeType = true;
                    $scope.createSolution.typeName = branch.label;
                    $scope.createSolution.typeId = branch.id;

                };

                $scope.data = tree_data;
                // console.log('$scope.data='+JSON.stringify($scope.data));

                $scope.showknowledgeType = false;

                $scope.chooseknowledge = function() {
                    $scope.showknowledgeType = !$scope.showknowledgeType;
                }
                $scope.close = function() {
                    $scope.showknowledgeType = false;
                };
                if (angular.isUndefined($scope.numberValue)) {
                    APIService.workernumber('zsk').then(function(response) {
                        var data = response.data;
                        // console.log('data='+JSON.stringify(data));
                        $scope.createSolution.number = data;
                    });
                }
                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };

                $scope.uploader = uploader;
                // console.log('$scope.uploader='+JSON.stringify($scope.uploader));

                // Called when the editor is completely ready.
                $scope.onReady = function() {
                    // ...

                };

                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];
                $scope.ok = function() {
                    if (validate($scope.createSolution)) {
                        $modalInstance.close($scope.createSolution);
                        $scope.createSolution = {};
                    } else {
                        Alert.swal({
                            title: "数据校验错误",
                            text: "知识库数据有数据未通过校验,请重新输入提示框数据",
                            type: "warning"
                        });
                    }

                };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };

                var fields = [
                    { key: 'title', required: true },
                    { key: 'keys', required: true },
                    { key: 'typeId', required: true },
                    { key: 'range', required: true },
                    { key: 'number', required: true },
                    { key: 'content', required: false },
                    { key: 'file', required: false }
                ];
                var fieldError = {};

                $scope.showError = function(formfield) {
                    return fieldError[formfield] || false;
                };

                var validate = function(createSolution) {
                    var error = true;
                    fieldError = {};
                    if (createSolution) {
                        angular.forEach(fields, function(item) {
                            if (item.required) {
                                if (item.key == 'file') {
                                    if (uploader.getNotUploadedItems().length == 0) {
                                        error = false;
                                        fieldError[item.key] = true;
                                    }
                                } else {
                                    if (angular.isUndefined(createSolution[item.key]) || createSolution[item.key] == null || createSolution[item.key] == '') {
                                        fieldError[item.key] = true;
                                        error = false;
                                    }
                                }
                            }
                        });
                    } else {
                        error = false;
                    }
                    if (!error) {
                        $scope.$apply($scope.showError);
                    }
                    return error;
                }


            },
            size: size,
            resolve: {
                uploader: function() {
                    return $scope.uploader;
                },
                tree_data: function() {
                    // console.log($scope.tree_data);
                    return angular.copy($scope.tree_data);
                },
                APIService: function() {
                    return api_bpm_domain;
                },
                currentUser: function() {
                    return loginUser.id;
                },
                Alert: function() {
                    return SweetAlert;
                }
            }
        });

        modalInstance.result.then(function(selectedItem) {
            if (selectedItem) {
                if ($scope.uploader.getNotUploadedItems().length > 0) {
                    $scope.uploader.formData = [
                        { 'title': selectedItem.title },
                        { 'createrUserId': selectedItem.createrUserId },
                        { 'content': selectedItem.content },
                        { 'hits': 0 },
                        { 'keywords': selectedItem.keys },
                        { 'solutionNumber': selectedItem.number },
                        { 'typeId': selectedItem.typeId },
                        { 'status': 1 },
                        { 'relateId': 0 },
                        { 'vision': 0 },
                        { 'solutionRange': selectedItem.range.id }
                    ];

                    $scope.uploader.onBeforeUploadItem = function(item) {
                        item.formData = $scope.uploader.formData;
                        item.formData.push({ 'fileName': item.file.name });
                    };
                    $scope.uploader.onSuccessItem = function(item, response, status, headers) {
                        if (response.status == 201) {
                            //success;
                            SweetAlert.swal({
                                title: "增加成功!",
                                text: "新建知识库成功!",
                                type: "success"
                            }, function() {
                                $scope.reload();
                            });
                        } else {
                            //error
                            SweetAlert.swal({
                                title: "增加失败!",
                                text: "新建知识库失败!",
                                type: "error"
                            });
                        }
                        //console.log(response);
                    }
                    $scope.uploader.uploadAll();
                } else {
                    var data = {
                        'title': selectedItem.title,
                        'createrUserId': selectedItem.createrUserId,
                        'content': selectedItem.content,
                        'hits': 0,
                        'keywords': selectedItem.keys,
                        'solutionNumber': selectedItem.number,
                        'typeId': selectedItem.typeId,
                        'status': 1,
                        'relateId': 0,
                        'vision': 0,
                        'solutionRange': selectedItem.range.id
                    };
                    api_solution.addNotFile(data).then(function(response) {
                        if (response.status == 201) {
                            var myData = Restangular.stripRestangular(response);
                            // console.log('myData='+JSON.stringify(myData));
                            SweetAlert.swal({
                                title: "增加成功!",
                                text: "新建知识库成功!",
                                type: "success"
                            }, function() {
                                $scope.reload();
                            });
                        } else {
                            //error
                            SweetAlert.swal({
                                title: "增加失败!",
                                text: "新建知识库失败!",
                                type: "error"
                            });
                        }
                    });
                }
            }


        }, function() {
            //console.log('Modal dismissed at: ' + new Date());
        });
    }



    $scope.my_tree = tree = {};
    $scope.try_async_load = function() {
        $scope.my_data = [];
        $scope.doing_async = true;

        api_user_data.fetchDataList('group', {
            "idx": 0,
            "sum": 1000
        }).then(function(response) {
            var myData = Restangular.stripRestangular(response);
            var list = myData.list;
            var objects = [];
            for (var i = 0; i < list.length; i++) {
                var object = {};
                object.id = list[i].id;
                if (list[i].parent == 0) {
                    object.parent = "#";
                } else {
                    object.parent = list[i].parent;
                }
                object.text = list[i].groupName;
                object.typeName = "group";
                object.state = {
                    "opened": true
                };
                objects.push(object);
            }
            $scope.groups = objects;
        });

        api_solution.findSolutionTypeActions(loginUser.id).then(function(response) {
            var data = response.data;
            // console.log('data='+JSON.stringify(data));
            var objects = [];

            for (var i = 0; i < data.length; i++) {
                var object = {};
                object.id = data[i][0];
                if (data[i][1] != 0) {
                    object.parent = data[i][1];
                }
                // if (object.parent == 0) {
                //     object.parent = "#";
                // }
                object.label = data[i][2];
                object.actions = data[i][3]; //权限部分
                object.group = "1";
                object.user = "2";
                object.state = {
                    "opened": true
                };
                object.typeName = "type";
                // if()
                if (object.actions.indexOf("2") >= 0) { //知识库类型 具有增加权限--系统管理员
                    $scope.showAddSolutionType = true;
                }
                if (object.actions.indexOf("5") >= 0) { //知识库类型 具有授权权限--系统管理员
                    $scope.showReviewKnowledgeType = true;
                }
                objects.push(object);
            }
            $scope.my_data = convertParentToChildList(objects);
            $scope.tree_data = angular.copy($scope.my_data);
            if ($scope.my_data.length > 0) {
                $scope.doing_async = false;
            }
        });



        $scope.showAddSolutionType = false; //添加知识类型 按钮
        $scope.showReviewKnowledgeType = false; //审核知识类型 按钮


    };

    $scope.try_async_load();

    $scope.ldloading = {};

    $scope.allfilterData = {
        key: 'null',
        status: 0,
        pageIndex: 0,
        pageSum: 10,
        //treeIds:'[]', 
        userId: loginUser.id
    }
    var filterData = {
        key: 'null',
        status: 0,
        pageIndex: 0,
        pageSum: 10,
        //treeIds:'[]', 
        userId: loginUser.id
    }
    $scope.statuses = [
        { status: 1, label: '待审核' },
        { status: 2, label: '已批准' },
        { status: 3, label: '已发布' },
        { status: 4, label: '已取消' },
        { status: 5, label: '已驳回' },
        { status: 6, label: '已拒绝' }
    ];

    $scope.$watch('searchSolutionInput', function(oldvalue, newvalue) {
        // console.log(' oldvalue='+JSON.stringify( oldvalue));
        // console.log(' newvalue='+JSON.stringify( newvalue));
        // if(oldvalue==newvalue) return;
        if (angular.isUndefined(oldvalue) || oldvalue == '') {
            filterData.key = 'null';
        } else {
            filterData.key = oldvalue;
        }
    });

    $scope.filterSolutionStatus = function(filterStatus) {
        var tempData = angular.copy(filterData);
        tempData.status = filterStatus;
        console.log(tempData);
        console.log(filterData);
        $scope.allfilterData = tempData;
        sessionStorage['searchknowledge'] = JSON.stringify(tempData);
        $scope.refreshListData('expand-right', tempData);
    }

    $scope.searchSolution = function() {
        $scope.refreshListData('expand-right', filterData);
    }

    $scope.reload = function() {
        if (sessionStorage.searchknowledge) { filterData = JSON.parse(sessionStorage.searchknowledge); }
        $scope.refreshListData('expand-right', filterData);
    }
    $scope.reload();

}]);

app.controller('knowledgeForumCtrl', ["$rootScope", "$scope", "$state", "$timeout", "$interval", "$modal", "SweetAlert", "moment", "Restangular", "api_solution", function($rootScope, $scope, $state, $timeout, $interval, $modal, SweetAlert, moment, Restangular, api_solution) {
    var loginUser = $rootScope.user;
    $scope.clses = [{
            id: 6,
            cls: 'danger'
        }, {
            id: 2,
            cls: 'warning'
        }, {
            id: 3,
            cls: 'success'
        },
        {
            id: 4,
            cls: 'primary'
        }, {
            id: 5,
            cls: 'info'
        }, {
            id: 1,
            cls: 'danger'
        }
    ];

    $scope.showlist = true;
    $scope.searchSolution = function(searchKey, page) {
            console.log(page)
            if (searchKey == "") {
                if (angular.isDefined(page)) {
                    if (page == 0) {
                        page = 1;
                    } else if (page == $scope.pages + 1) {
                        page = $scope.pages;
                    }
                } else {
                    tempPage = page = 0;
                    $scope.solutionBBS = [];
                }
                api_solution.queryBBSSolutions(tempPage, 7, 'createTime', loginUser.id, searchKey).then(function(response) {
                    var myData = Restangular.stripRestangular(response);
                    var status = myData.status;
                    if (status == "500") {
                        $scope.solutionBBS = [];
                    } else if (status == "200") {
                        var data = myData.data[0];
                        var count = myData.data[1];
                        $scope.pages = parseInt(count / 7) + 1;
                        if (page == 0) {
                            $scope.currentPage = page + 1;
                        } else {
                            $scope.currentPage = page;
                        }
                        if (data.length > 0) {
                            $scope.solutionBBS = [];
                            for (var i = 0; i < data.length; i++) {
                                data[i].creationTime = getLocalTime(data[i].creationTime);
                                if (data[i].lastReplyTime == null) {
                                    data[i].lastReplyTime = "暂无回复";
                                } else {
                                    data[i].lastReplyTime = getLocalTime(data[i].lastReplyTime);
                                }
                                if (data[i].lastReplyUser == null) {
                                    data[i].lastReplyUser = "暂无回复人";
                                }
                                if (i == 0) {
                                    data[i].index = 1;
                                } else if (i == 1) {
                                    data[i].index = 2;
                                } else if (i == 2) {
                                    data[i].index = 3;
                                } else {
                                    data[i].index = 4;
                                }
                                $scope.solutionBBS.push(data[i]);
                            }
                        }
                    }
                });
            } else if (searchKey != "" && searchKey.length > 1) {
                if (angular.isDefined(page)) {
                    if (page == 0) {
                        page = 1;
                    } else if (page == $scope.pages + 1) {
                        page = $scope.pages;
                    }
                    tempPage = page - 1;
                } else {
                    tempPage = page = 0;
                    $scope.solutionBBS = [];
                }
                //  if(page==0){
                //   page=1;
                // }else if(page==$scope.pages+1){
                //   page=$scope.pages;
                // }
                api_solution.queryBBSSolutions(tempPage, 7, 'createTime', loginUser.id, searchKey).then(function(response) {
                    var myData = Restangular.stripRestangular(response);
                    var status = myData.status;
                    if (status == "500") {
                        $scope.solutionBBS = [];
                    } else if (status == "200") {
                        var data = myData.data[0];
                        var count = myData.data[1];
                        $scope.pages = parseInt(count / 7) + 1;
                        if (page == 0) {
                            $scope.currentPage = page + 1;
                        } else {
                            $scope.currentPage = page;
                        }
                        if (data.length > 0) {
                            $scope.solutionBBS = [];
                            for (var i = 0; i < data.length; i++) {
                                data[i].creationTime = getLocalTime(data[i].creationTime);
                                if (data[i].lastReplyTime == null) {
                                    data[i].lastReplyTime = "暂无回复";
                                } else {
                                    data[i].lastReplyTime = getLocalTime(data[i].lastReplyTime);
                                }
                                if (data[i].lastReplyUser == null) {
                                    data[i].lastReplyUser = "暂无回复人";
                                }
                                if (i == 0) {
                                    data[i].index = 1;
                                } else if (i == 1) {
                                    data[i].index = 2;
                                } else if (i == 2) {
                                    data[i].index = 3;
                                } else {
                                    data[i].index = 4;
                                }
                                $scope.solutionBBS.push(data[i]);
                            }
                        }
                    }
                });
            }
        }
        // $scope.$watch('searchInput',function(newvalue, oldvalue){
        //   if(newvalue == oldvalue) return;
        //   $scope.searchSolution(newvalue);
        // });





    //BBS列表切换
    $scope.changeShowList = function(val) {
        $scope.showlist = !$scope.showlist;
    }

    $scope.solutionBBS = [];
    $scope.hotRankings = [];
    $scope.scoreRankings = [];
    $scope.solutionScores = [];
    $scope.currentPage = 1;
    $scope.pages = 0;
    api_solution.fetchBBSSolutions(0, 7, "createTime", loginUser.id).then(function(response) {
        $scope.solutionBBS = [];
        var myData = Restangular.stripRestangular(response);
        var data = myData.data[0];
        var count = myData.data[1];
        if (count <= 7) {
            $scope.pages = 1;
        }
        // for(var i=0;i<count/7;i++){
        //   pages.push(i);
        // }

        // var sum = myData.data[1]/7;
        // $scope.pages=parseInt(sum);
        // if(sum>$scope.pages){
        //   $scope.pages=$scope.page+1;
        // }else if(sum==$scope.pages){
        //   $scope.pages=$scope.page;
        // }
        // console.log($scope.pages);
        for (var i = 0; i < data.length; i++) {
            data[i].creationTime = getLocalTime(data[i].creationTime);

            if (data[i].lastReplyTime == null) {
                data[i].lastReplyTime = "暂无回复";
            } else {
                data[i].lastReplyTime = getLocalTime(data[i].lastReplyTime);
            }
            if (data[i].lastReplyUser == null) {
                data[i].lastReplyUser = "暂无回复人";
            }
            if (i == 0) {
                data[i].index = 1;
            } else if (i == 1) {
                data[i].index = 2;
            } else if (i == 2) {
                data[i].index = 3;
            } else {
                data[i].index = 4;
            }

            $scope.solutionBBS.push(data[i]);
        }
    });
    $scope.fetchByPage = function(page) {
        api_solution.fetchBBSSolutions(0, 7, "createTime", loginUser.id).then(function(response) {
            var sumdata = Restangular.stripRestangular(response);
            var sum = sumdata.data[1];
            if (angular.isDefined($scope.searchInput) && $scope.searchInput != "" && $scope.searchInput.length > 1) {
                $scope.searchSolution($scope.searchInput, page);
            } else {
                if (page == 0) {
                    page = 1;
                } else if (page == $scope.pages + 1) {
                    page = $scope.pages;
                } else if (sum / 7 == 1) {
                    $scope.pages = 1;
                    page = 1;
                }
                api_solution.fetchBBSSolutions(page - 1, 7, "createTime", loginUser.id).then(function(response) {
                    $scope.solutionBBS = [];
                    var myData = Restangular.stripRestangular(response);
                    var data = myData.data[0];
                    var count = myData.data[1];
                    if (count / 7 == parseInt(count / 7)) {
                        // if(count/7==1){
                        // 	page=1;
                        // 	$scope.pages=parseInt(count/7);
                        //  }else{
                        $scope.pages = parseInt(count / 7);
                        // }
                    } else {
                        $scope.pages = parseInt(count / 7) + 1;
                    }
                    $scope.currentPage = page;

                    for (var i = 0; i < data.length; i++) {
                        data[i].creationTime = getLocalTime(data[i].creationTime);
                        if (data[i].lastReplyTime == null) {
                            data[i].lastReplyTime = "暂无回复";
                        } else {
                            data[i].lastReplyTime = getLocalTime(data[i].lastReplyTime);
                        }
                        if (data[i].lastReplyUser == null) {
                            data[i].lastReplyUser = "暂无回复人";
                        }
                        if (i == 0) {
                            data[i].index = 1;
                        } else if (i == 1) {
                            data[i].index = 2;
                        } else if (i == 2) {
                            data[i].index = 3;
                        } else {
                            data[i].index = 4;
                        }
                        $scope.solutionBBS.push(data[i]);
                    }
                });
            }

        })

    }

    api_solution.fetchBBSSolutions(0, 5, "scores", loginUser.id).then(function(response) {
        $scope.solutionBBS1 = [];
        var myData = Restangular.stripRestangular(response);
        var data = myData.data;
        for (var i = 0; i < data.length; i++) {
            data[i].creationTime = getLocalTime(data[i].creationTime);
            data[i].lastReplyTime = getLocalTime(data[i].lastReplyTime);
            if (i == 0) {
                data[i].index = 1;
            } else if (i == 1) {
                data[i].index = 2;
            } else if (i == 2) {
                data[i].index = 3;
            } else {
                data[i].index = 4;
            }
            $scope.solutionScores.push(data[i]);
        }
    });

    api_solution.hotRanking(5).then(function(response) {
        var myData = Restangular.stripRestangular(response);
        var data = myData.data;
        console.log(data);
        $scope.hotRankings = [];

        $scope.hotArray = [];
        for (var i = 0; i < data.length; i++) {
            data[i].createTime = getLocalTime(data[i].createTime);
            if (i == 0) {
                data[i].index = 1;
            } else if (i == 1) {
                data[i].index = 2;
            } else if (i == 2) {
                data[i].index = 3;
            } else {
                data[i].index = 4;
            }
            $scope.hotRankings.push(data[i]);
            $scope.hotArray.push(data[i].replies);
        }
        if ($scope.hotArray.length > 0) {
            $scope.tophot = $scope.hotArray.join(',');
        }
        //$scope
        //$scope.hotArray=[275,490,397,487,339,403,402,312,300,294,411,367,319,416,355,416,371,479,279,361,312,269,402,327,474,422,375,283,384,372];
        //热点排行榜 
        // $("#stats-sparklines-2").pixelSparkline($scope.hotArray, {
        //    type: 'bar',
        //    height: '36px',
        //    width: '100%',
        //    barSpacing: 2,
        //    zeroAxis: false,
        //    barColor: '#ffffff'
        //  });
    });

    api_solution.scoreRanking(5).then(function(response) {
        var myData = Restangular.stripRestangular(response);
        var data = myData.data;
        $scope.scoreRankings = [];
        $scope.scoreArray = [];
        for (var i = 0; i < data.length; i++) {
            data[i].createTime = getLocalTime(data[i].createTime);
            if (i == 0) {
                data[i].index = 1;
            } else if (i == 1) {
                data[i].index = 2;
            } else if (i == 2) {
                data[i].index = 3;
            } else {
                data[i].index = 4;
            }
            $scope.scoreRankings.push(data[i]);
            $scope.scoreArray.push(data[i].scores);
        }
        if ($scope.scoreArray.length > 0) {
            $scope.topscore = $scope.scoreArray.join(',');
        }
        //$scope.scoreArray=[275,490,397,487,339,403,402,312,300];
        //评分排行榜
        // $("#stats-sparklines-3").pixelSparkline($scope.scoreArray, {
        //               type: 'line',
        //               width: '100%',
        //               height: '45px',
        //               fillColor: '',
        //               lineColor: '#fff',
        //               lineWidth: 2,
        //               spotColor: '#ffffff',
        //               minSpotColor: '#ffffff',
        //               maxSpotColor: '#ffffff',
        //               highlightSpotColor: '#ffffff',
        //               highlightLineColor: '#ffffff',
        //               spotRadius: 4,
        //               highlightLineColor: '#ffffff'
        //             });
    });

    var currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
    var currentDate = moment().format('YYYY-MM-DD');

    var addDate = function(dayCount) {
        return moment().add(dayCount, 'days').format('YYYY-MM-DD');
    }

    var getLocalTime = function(time) {
        return moment(time).format('YYYY-MM-DD HH:mm:ss');
        // console("time="+time)
    }



    //---------------浏览数与回复数 以及知识库总数------------------------------------------
    api_solution.findSolutionDataByDateById(currentDate, 0).then(function(response) {
        var myData = Restangular.stripRestangular(response);
        var data = myData.data;
        $scope.todayHits = data[0].hitnums;
        $scope.todayReplys = data[0].replynums;
        if (angular.isUndefined(data[0].hitnums)) { $scope.todayHits = 0; }
        if (angular.isDefined(data[1]) && angular.isDefined(data[1].num)) {
            $scope.num = data[1].num;
            var monthData = data[1].monthData;
        } else {
            $scope.num = 0;
        }



        //月度排行榜
        var uploads_data = [];
        if (angular.isDefined(monthData)) {
            for (var i = 0; i < monthData.length; i++) {
                uploads_data.push(monthData[i]);
            }
        }

        // var uploads_data = [
        //          { day: '2015-03-10', v: 20 },
        //          { day: '2015-03-11', v: 10 },
        //          { day: '2015-03-12', v: 15 },
        //          { day: '2015-03-13', v: 12 },
        //          { day: '2015-03-14', v: 5  },
        //          { day: '2015-03-15', v: 5  },
        //          { day: '2015-03-16', v: 20 }
        //  ];

        if (!angular.isUndefined(angular.element("#hero-graph")[0])) {
            // Morris.Line({
            //          element: 'hero-graph',
            //          data: uploads_data,
            //          xkey: 'day',
            //          ykeys: ['v'],
            //          labels: ['Value'],
            //          lineColors: ['#fff'],
            //          lineWidth: 2,
            //          pointSize: 4,
            //          gridLineColor: 'rgba(255,255,255,.5)',
            //          resize: true,
            //          gridTextColor: '#fff',
            //          xLabels: "day",
            //          xLabelFormat: function(d) {
            //            return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov', 'Dec'][d.getMonth()] + ' ' + d.getDate(); 
            //          },
            //   });  
        };
    });

    api_solution.findSolutionDataByDateById(addDate(-1), 0).then(function(response) {
        var myData = Restangular.stripRestangular(response);
        var data = myData.data;
        if (data) {
            $scope.lastHits = data[0].hitnums;
            $scope.lastReplys = data[0].replynums;
            if (angular.isUndefined(data[0].hitnums)) { $scope.lastHits = 0; }
        }
    });

    //折叠
    $scope.isCollapsed = false; //'显示趋势图'默认折叠
    $scope.btnName = "隐藏趋势图";
    $scope.showBtnClk = function() {
        $scope.isCollapsed = !$scope.isCollapsed;
        // 改变按钮文字
        if ($scope.isCollapsed) {
            $scope.btnName = "展现趋势图";
        } else {
            $scope.btnName = "隐藏趋势图";
        }
    };

    $scope.commentshowSolution = function(solution) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/knowledge/tpl/commentknowledge.html',
            controller: function($scope, $modalInstance, APIService, uploader, currentUser, Alert, MomentFormat) {
                // $scope.uploader = uploader;  
                var loadData = function() {
                    $scope.visions = [];
                    $scope.entity = {};
                    $scope.solutionDowpath = APIService.getSolutionDowpath().getRequestedUrl();
                    APIService.findSolutionById(solution.id).then(function(response) {
                        var datas = response.data[0];
                        console.log(datas);
                        $scope.visions = datas;
                        // console.log(datas);
                        // var data={};
                        // for(var i=0;i<datas.length-1;i++){
                        //      if(solution.id==datas[i].id){
                        //          data=datas[i];
                        //      }
                        // }
                        solution.hits = datas.hits;
                        $scope.entity = {
                            "id": datas.id,
                            "title": datas.title,
                            "keys": datas.keywords,
                            "type": datas.typeId,
                            "range": datas.solutionRange,
                            "number": datas.solutionNumber,
                            "content": datas.content,
                            "createrUserId": datas.createrUserId,
                            "createrUserName": datas.createrUserName,
                            "createTime": datas.createTime,
                            "status": datas.status,
                            "hits": datas.hits,
                            "relateId": datas.relateId,
                            "vision": datas.vision,
                            "vision2": "V" + datas.vision,
                            // "fileContent":datas.fileContent,
                            "replies": datas.replies,
                            "scores": datas.scores,
                            "hits": datas.hits,
                            "fileName": datas.fileName,
                            "typeName": datas.typename
                        };
                        setInterval(function() {
                            if ($scope.entity.content == "") {
                                $scope.entity.content = datas.content
                                $scope.$apply()
                            }
                        }, 1000);
                        // $scope.entity.content=datas.content
                        console.log($scope.entity);
                    });
                    // $scope.$$phase ||$scope.$apply()
                    // APIService.getSolutionType(data.typeId).then(function(responseData){
                    //        var dd=responseData.data;
                    //        typeName=dd.typeName;
                    //         // console.log(dd);
                    //       $scope.entity.typeName=typeName;
                    //$scope.$apply();
                    //$scope.$digest();
                    // console.log($scope.entity);
                    $scope.comments = [];
                    APIService.findSolutionReviewById(solution.id).then(function(response) {
                        // console.log(response.status);
                        if (response.status != "500") {
                            var data = response.data;
                            for (var i = 0; i < data.length; i++) {
                                var object = {};
                                object.id = data[i].id;
                                object.name = data[i].name;
                                // object.content=data[i].review;
                                var ss = data[i].review;
                                var s1 = "";
                                if (ss != null) {
                                    var index = ss.indexOf("<p>");
                                    var indexs = ss.indexOf("</p>");
                                    s1 = ss.substring(index + 3, indexs);
                                }
                                object.content = s1;
                                object.score = data[i].reviewScore;
                                object.time = data[i].reviewTime;
                                // console.log('object.time='+JSON.stringify(object));
                                $scope.comments.push(object);
                            }
                        }
                    });

                    $scope.showCommentScore = true;
                    //查询用户是否已经评过分
                    $scope.findCommentScore = function() {
                        $scope.showCommentScore = true;
                        APIService.checkCommentScoreByUserIds(currentUser, solution.id).then(function(response) {
                            var data2 = response.data;
                            if (data2.length > 0) {
                                $scope.showCommentScore = false;
                                // console.log( " findCommentScore "+data);
                                //$scope.comments = data;
                            }
                        });
                    }

                    $scope.findCommentScore();
                    // });
                    // });
                }

                loadData();

                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };
                $scope.uploader = uploader;

                // Called when the editor is completely ready.
                // $scope.onReady = function () {
                //     // ...

                // };

                $scope.ranges = [{
                    "id": 1,
                    "name": "全局"
                }, {
                    "id": 3,
                    "name": "组"
                }];


                // $scope.ok = function() {
                //   $modalInstance.close($scope.entity);                
                // };

                $scope.cancel = function() {
                    // api_solution.findSolutions($scope.entity.id).then(function(response){
                    //                   var data6=response.data[0]; 
                    //                   for(var j=0;j<=$scope.solutionBBS.length;j++){
                    //                     if($scope.solutionBBS.length>0&&$scope.solutionBBS[j].id==$scope.entity.id){
                    //                       $scope.solutionBBS[j].replies=data6.replies;
                    //                       $scope.solutionBBS[j].hits=data6.hits;
                    //                       $scope.solutionBBS[j].scores=data6.scores;
                    //                       break;
                    //                     }
                    //                   }
                    //                 });
                    $modalInstance.close($scope.entity.id);
                };

                $scope.saveComment = function(reviewcontent, score) {
                    $scope.entity['reviewcontent'] = reviewcontent;
                    $scope.entity['score'] = score;
                    $modalInstance.close($scope.entity);
                }
            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                uploader: function() {
                    return $scope.uploader;
                },
                currentUser: function() {
                    return loginUser.id;
                },
                Alert: function() {
                    return SweetAlert;
                },
                MomentFormat: function() {
                    return moment;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            if (selectedItem.title) {
                var solutionId = selectedItem.id;
                var reviewContent = selectedItem.reviewcontent;
                // if(solutionId==null){
                var data = {
                    id: null,
                    solutionId: solutionId,
                    userId: loginUser.id,
                    review: reviewContent,
                    reviewScore: selectedItem.score,
                    reviewTime: new Date()
                };
                api_solution.addSolutionReview(data).then(function(response) {
                    var status = response.status;
                    console.log(response)
                    console.log('$scope.apClient=' + JSON.stringify(status));
                    if (status == "201") {
                        SweetAlert.swal({
                            title: "评论知识库!",
                            text: "评论知识库成功!",
                            type: "success"
                        }, function() {
                            api_solution.findSolutions(selectedItem.id).then(function(response) {
                                var data6 = response.data[0];
                                for (var j = 0; j <= $scope.solutionBBS.length; j++) {
                                    if ($scope.solutionBBS.length > 0 && $scope.solutionBBS[j].id == selectedItem.id) {
                                        $scope.solutionBBS[j].replies = data6.replies;
                                        $scope.solutionBBS[j].hits = data6.hits;
                                        $scope.solutionBBS[j].scores = data6.scores;
                                        break;
                                    }
                                }
                            });
                        });
                    } else {
                        SweetAlert.swal({
                            title: "评论知识库!",
                            text: "评论知识库失败!",
                            type: "error"
                        });
                    }
                });
            }
        });


    }


    //TODO
    $('#attach-check').on('change', function() {
        $('#attach').toggleClass('hidden');
    });

    $('#attachcheck1').on('change', function() {
        $('#attachdiv1').toggleClass('hidden');
    });

    $('#attachcheck2').on('change', function() {
        $('#attachdiv2').toggleClass('hidden');
    });

}]);

app.filter('index', function() {
    return function(array) {
        return (array || []).map(function(item, index) {
            item.order = index + 1;
            return item;
        });
    };
});


app.controller('GridOperatorCtrl', ['$http', '$scope', function($http, $scope, $event) {

    if ($scope.item.actions != "" && $scope.item.actions != null) { //1:查看，2:操作(改)；3:审核；4.过期；发布更新
        if ($scope.item.actions.indexOf("1") >= 0) { //查看权限
            $scope.item.detailPower = true;
        } else {
            $scope.item.detailPower = false;
        }

        if ($scope.item.status == 4) {
            $scope.item.commentPower = true;
        } else {
            $scope.item.commentPower = false;
        }
        if ($scope.item.actions.indexOf("2") >= 0) { //操作(改)
            if ($scope.item.status == 1 || $scope.item.status == 5 || $scope.item.status == 3) {
                $scope.item.updatePower = true;
            }
        } else {
            $scope.item.updatePower = false;
        }
        if ($scope.item.actions.indexOf("3") >= 0) { //审核
            if ($scope.item.status == 1) {
                $scope.item.reviewPower = true;
            }
        } else {
            $scope.item.reviewPower = false;
        }
        if ($scope.item.actions.indexOf("4") >= 0) { //过期与发布
            if ($scope.item.status == 2) {
                $scope.item.updatePower = true;
                $scope.item.outTimePower = true;
            }
        } else {
            $scope.item.outTimePower = false;
        }
    }

    if ($scope.item.status == 3) { //已发布的才能评论
        $scope.item.publishnotPower = true;
        $scope.item.commontPower = true;
    } else {
        $scope.item.commontPower = false;
        $scope.item.publishnotPower = false;
    }
    // console.log($scope.item.status + "  " + $scope.item.commontPower);

    $scope.edit = function() {
        $scope.colobject.grid.appScope.editSolution($scope.item.id);
        // console.log($scope.colobject);
        //$scope.doEdit($scope.item.id);
    }

    $scope.comment = function() {
        $scope.colobject.grid.appScope.commentSolution($scope.item.id);
        //$scope.doComment($scope.item.id);
    }

    $scope.approval = function() {
        $scope.colobject.grid.appScope.approvalSolution($scope.item.id, $scope.item.outTimePower);
        //$scope.doApproval($scope.item.id,$scope.item.outTimePower);
    }
    $scope.publish = function() {
        $scope.colobject.grid.appScope.approvalSolution($scope.item.id, $scope.item.outTimePower);
        //$scope.doApproval($scope.item.id,$scope.item.outTimePower);
    }
    $scope.publishnot = function() {
        $scope.colobject.grid.appScope.approvalSolution($scope.item.id, $scope.item.outTimePower);
        //$scope.doApproval($scope.item.id,$scope.item.outTimePower);
    }
    $scope.detail = function() {
        $scope.colobject.grid.appScope.detailSolution($scope.item.id);
        // console.log($scope.colobject);
    }
}]);

app.directive('gridoperator', function() {
    return {
        restrict: 'E',
        scope: {
            item: '=',
            colobject: '='
                // doEdit: '&',
                // doComment: '&',
                // doApproval: '&'
        },
        controller: 'GridOperatorCtrl',
        template: '<div class="links cl-effect-1 ui-grid-cell-contents">' +
            '<a ng-click="detail()" ng-show="{{item.detailPower}}" tooltip="查看" tooltip-placement="right"><i class="ti-eye"></i></a>' +
            '<a ng-click="edit()" ng-show="{{item.updatePower}}" tooltip="编辑" tooltip-placement="right"><i class="fa fa-pencil"></i></a>' +
            '<a ng-click="comment()" ng-show="{{item.commontPower}}" tooltip="评论" tooltip-placement="right"><i class="fa fa-send"></i></a>' +
            '<a ng-click="approval()" ng-show="{{item.reviewPower}}" tooltip="审核" tooltip-placement="right"><i class="fa fa-ellipsis-v"></i></a>' +
            '<a ng-click="publish()" ng-show="{{item.outTimePower}}" tooltip="发布" tooltip-placement="right"><i class="ti-clipboard"></i></a>' +
            '<a ng-click="publishnot()" ng-show="{{item.publishnotPower}}" tooltip="撤销" tooltip-placement="right"><i class=" ti-brush-alt"></i></a>' +
            '</div>'
    };
});